package com.ykt.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.ykt.model.Address;
import com.ykt.model.UserAddress;
@ControllerBind(controllerKey="/userAddress")
public class UserAddressController extends BaseController<UserAddress>{
	public UserAddressController() {
		super(UserAddress.class);
	}

	public void grid() {
        int page = getParaToInt("page", 1);
        int rows = this.getParaToInt("rows", 20);
        try {
            Page<UserAddress> date = findPageData(page, rows, this.toParaMap());
//            Page<UserAddress> date = UserAddress.dao.pageFindModel(page, rows, this.toParaMap());
            rendDataGrid(date);
        } catch (Exception e) {
            log.error(e);
            rendJson(false, e.getMessage());
        }
    }
	
	public Page<UserAddress> findPageData(int page, int rows,  Map<String, String> paramMap){
		
		Page<UserAddress> date = UserAddress.dao.pageFindModel(page, rows, this.toParaMap());
		List<Integer> ids = new ArrayList<>();
        for (UserAddress userAddress : date.getList()) {

            int provinceId = userAddress.getInt("province_id");
            int cityId = userAddress.getInt("city_id");
            int districtId = userAddress.getInt("district_id");
            if(!ids.contains(provinceId)){
                ids.add(provinceId);
            }
            if(!ids.contains(cityId)){
                ids.add(cityId);
            }
            if(!ids.contains(districtId)){
                ids.add(districtId);
            }
        }
        List<Address> addresses = Address.dao.findByIds(ids);
        if(addresses == null || addresses.isEmpty()){
            return date;
        }
        
        Map<Integer, Address> addressMap = new HashMap<>();
        for (Address address : addresses) {
            addressMap.put(address.getInt("id"), address);
        }

        for (UserAddress userAddress : date.getList()) {
        	int provinceId = userAddress.getInt("province_id");
            int cityId = userAddress.getInt("city_id");
            int districtId = userAddress.getInt("district_id");

            userAddress.put("provinceName", addressMap.get(provinceId).get("name"));
            userAddress.put("cityName", addressMap.get(cityId).get("name"));
            userAddress.put("districtName", addressMap.get(districtId).get("name"));
        }
		return date;
		
	}

}
